package me.linczh.framework.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jdom.Document;
import org.jdom.Element;

public class ActionMapping {
	private volatile static ActionMapping instance = null;
	private Map<String, ActionItem> map;
	
	private ActionMapping() {}
	
	public static ActionMapping getInstance() {
		if (instance == null) {
			synchronized (ActionMapping.class) {
				if (instance == null) instance = new ActionMapping();
			}
		}
		return instance;
	}
	
	public ActionItem getActionItem(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String action = uri.substring(uri.lastIndexOf('/') + 1, uri.length() - ".action".length());
		System.out.println("URI: " + uri + "\nAction: " + action);
		return map.get(action);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void initActionsMapping(Document _doc) {
		if (map != null) return;
		map = new HashMap<String, ActionItem>();
		// parse
		Element root = _doc.getRootElement();
		List<Element> actions = root.getChildren("action");
		for (Element a : actions) {
			ActionItem aMap = new ActionItem();
			aMap.setActionName(a.getAttributeValue("name"));
			aMap.setActionClass(a.getAttributeValue("class"));
			aMap.setActionMethod(a.getAttributeValue("method"));
			List<Element> results = a.getChildren("result");
			Map<String, Map> resultMap = new HashMap<String, Map>();
			for (Element r : results) {
				Map<String, String> rMap = new HashMap<String, String>();
				rMap.put("name", r.getAttributeValue("name"));
				rMap.put("type", r.getAttributeValue("type"));
				rMap.put("result", r.getText());
				resultMap.put(rMap.get("name"), rMap);
			}
			aMap.setResultMap(resultMap);
			map.put(aMap.getActionName(), aMap);
		}
		System.out.println(map);
	}
}
